import requests
import json
from time import sleep
import pymongo
from tools.funciton import get_jiwu_token
from config.configs import ALPHA_DB_HOST, ALPHA_DB_PORT
from datetime import datetime
import time

jw = pymongo.MongoClient(ALPHA_DB_HOST, ALPHA_DB_PORT).jiwu


def get_zero_hour_timestamp(date_str):
    """
    获取指定日期零点的时间戳
    :param date_str: 格式为 'YYYY-MM-DD' 的日期字符串
    :return: 零点时间戳
    """
    # 将字符串转换为日期对象
    date_obj = datetime.strptime(date_str, '%Y-%m-%d')
    # 将日期对象转换为时间戳
    timestamp = int(time.mktime(date_obj.timetuple()))
    return timestamp


def return_to_flash_send(express_no, appoint_date):
    """直退转闪电批量发货"""
    nos = [i['appointNo'] for i in jw.appointments_dewu.find({'type': 4, 'status': 2})]
    print(nos)
    print(len(nos))
    token = get_jiwu_token()
    s = 0
    for no in nos:
        url = "https://erp.geehoop.com/api/backend/storage/appointment/dewu/deliver"
        payload = json.dumps({
            "appointNo": f"{no}",
            "expressType": "SF",
            "expressNo": str(express_no),
            "sellerPhone": "18683341301",
            "appointTime": get_zero_hour_timestamp(appoint_date)
        })
        headers = {
            'authorization': f'Bearer {token}',
            'priority': 'u=1, i',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'content-type': 'application/json',
            'Accept': '*/*',
            'Host': 'erp.geehoop.com',
            'Connection': 'keep-alive'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        s += 1
        print(response.text)
        print(f"==================第{s}次请求完成")
        sleep(0.3)


def speed_to_flash_send(express_no, appoint_date):
    """极速转闪电批量发货"""
    nos = [i['outStockNo'] for i in jw.stock_out_orders.find({'type': 1, 'status': 4})]
    token = get_jiwu_token()
    s = 0
    print(len(nos))
    print(nos)
    for no in nos:
        url = f"https://erp.geehoop.com/api/backend/stock_out_order/deliver/{no}"

        payload = json.dumps({
            "expressNo": express_no,
            "expressType": "SF",
            "appointTime": get_zero_hour_timestamp(appoint_date),
            "sellerPhone": "18683341301"
        })
        headers = {
            'authorization': f'Bearer {token}',
            'priority': 'u=1, i',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'content-type': 'application/json',
            'Accept': '*/*',
            'Host': 'erp.geehoop.com',
            'Connection': 'keep-alive'
        }
        response = requests.request("POST", url, headers=headers, data=payload)
        print(response.text)
        s += 1
        print(f"==================第{s}次请求完成")
        sleep(0.3)


return_to_flash_send('SF3163211424594', '2025-03-26')
# speed_to_flash_send('SF3159431507775', '2025-03-12')